package com.qingfeng.client.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.qingfeng.client.DO.*;
import com.qingfeng.client.VO.*;
import com.qingfeng.client.bean.*;
import com.qingfeng.client.dao.*;
import com.qingfeng.client.service.*;
import com.qingfeng.client.util.Page;
import com.qingfeng.coupon.entity.CouponTemplate;
import com.qingfeng.coupon.service.CouponService;
import com.qingfeng.util.OkhttpUtil;
import com.qingfeng.util.SignUtil;
import com.sun.corba.se.spi.ior.ObjectKey;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 对接之前的前端版本，使用老接口
 * 目前以及全部废弃
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/4/2 5:30 下午
 */
@Slf4j
@RestController
@RequestMapping("/")
public class OldApi extends BaseV1Api {

    @Autowired
    private CouponService couponService;

    @Resource
    private LogisticsCompanyMapper LogisticsCompanyDao;
    @Autowired
    private StoreService storeService;
    @Autowired
    private GoodsService goodsService;
    @Resource
    private ShippingAddressMapper shippingAddressDao;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private ShoppingCartMapper shoppingCartDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AfterSellService afterSellService;
    @Resource
    private AfterSellMapper afterSellMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Resource
    private OrderStoreMapper orderStoreMapper;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private LogisticsMapper logisticsMapper;
    @Resource
    private SellerMapper sellerMapper;
    @Autowired
    private ActivityService activityService;

    @Resource
    private StoreMapper storeMapper;

    @RequestMapping("/app/buyer/baseInfo")
    public Object baseInfo() {
        Buyer buyerBean = getUserByToken();
        System.out.println("=============获取用户信息=============== " + buyerBean);
        if (buyerBean == null) {
            return returnError("用户未登录");
        }
//        List list = orderStoreMapper.statNum(buyerBean.getId());
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("buyer",buyerBean);
//        jsonObject.put("stat",list);
        return returnObject(buyerBean);

    }


    @RequestMapping("/app/index/loadinfoApi")
    public Object loadinfoApi() {
        StoreIndexVo storeIndexVo = storeService.storeInfo(1L);
        Seller seller = sellerMapper.selectById(10);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("storeId", 1);
        jsonObject.put("goodsCommonList", storeIndexVo.getGoodsCommonList());
        jsonObject.put("goodsTypeBeans", storeIndexVo.getGoodsType());
        jsonObject.put("indexTypeBeans", storeIndexVo.getIndexType());
        jsonObject.put("storeBean", storeIndexVo.getStore());
        jsonObject.put("sellBean", seller);
        jsonObject.put("type", 0);
        jsonObject.put("count", 0);
        return jsonObject;
    }


    @RequestMapping(value = "/app/goods/share")
    @ResponseBody
    public Object shareGoodsDetail(@RequestBody String url) throws Exception {
        url = url.replace("\"","");
        System.out.println(url);
        String jsapi_ticket = SignUtil.getTicket();
        // 注意 URL 一定要动态获取，不能 hardcode
        //当前网页的url
        //服务器地址 //端口号 //项目名称 //请求页面或其他地址 //参数
        System.out.println(url);
        Map<String, String> res = SignUtil.sign(jsapi_ticket, url);
        System.out.println(res);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", 1);
        jsonObject.put("object", res);
        return jsonObject;
    }

    @RequestMapping("/app/goods/find")
    public Object find(@RequestBody JSONObject jsonObject) {
        Page page = parsePageJSON(jsonObject.getJSONObject("page"));
        JSONObject item = jsonObject.getJSONObject("item");
        GoodsConditionVo condition = new GoodsConditionVo();
        condition.setStoreId(item.getLong("storeId"));
        condition.setTypeId(item.getInteger("typeId"));
        condition.setName(item.getString("name"));
        IPage page1 = goodsService.getPage(page, condition);
        return returnPage(page1);
    }

    /**
     * 获取购物车
     *
     * @return
     */
    @RequestMapping("/web/shoppingCart/myCartV2")
    public Object myCartV2() {
        Buyer buyer = getUserByToken();
        List<ShoppingCartStoreDo> list = shoppingCartDao.getShopCatGoodsDoByBuyer(buyer.getId());
        return returnList(parseMyCartData(list));
    }

    //购物车数据转换成以前的
    private JSONArray parseMyCartData(List<ShoppingCartStoreDo> list) {
        JSONArray jsonArray = new JSONArray();
        for (ShoppingCartStoreDo shoppingCartStoreDo : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("store_id", shoppingCartStoreDo.getStoreId());
            jsonObject.put("store_icon", shoppingCartStoreDo.getStoreIcon());
            jsonObject.put("store_name", shoppingCartStoreDo.getStoreName());
            JSONArray items = new JSONArray();
            for (ShoppingCartGoodsDo shoppingCartGoodsDo : shoppingCartStoreDo.getGoodsDos()) {
                JSONObject goods = new JSONObject();
                goods.put("attrs", shoppingCartGoodsDo.getAttrs());
                goods.put("can_sell_size", shoppingCartGoodsDo.getCanSellSize());
                goods.put("cart_id", shoppingCartGoodsDo.getCartId());
                goods.put("create_time", shoppingCartGoodsDo.getCreateTime());
                goods.put("goods_common_id", shoppingCartGoodsDo.getGoodsCommonId());
                goods.put("goods_id", shoppingCartGoodsDo.getGoodsId());
                goods.put("name", shoppingCartGoodsDo.getName());
                goods.put("num", shoppingCartGoodsDo.getNum());
                goods.put("pic1", shoppingCartGoodsDo.getPic1());
                goods.put("price", shoppingCartGoodsDo.getPrice());
                goods.put("sell_stat", shoppingCartGoodsDo.getSellStat());
                goods.put("store_id", shoppingCartGoodsDo.getStoreId());
                items.add(goods);
            }
            jsonObject.put("list", items);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }


    @RequestMapping("/app/goods/detailV2")
    public Object detailV2(@RequestParam Long goodsCommonId) {
        Buyer buyer = getUser();
        GoodsDetailAllInfo goodsDetailAllInfo = goodsService.detail(goodsCommonId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("attrs", attrs(goodsDetailAllInfo.getAttrs()));
        jsonObject.put("goods", goods(goodsDetailAllInfo.getGoodsDetailDos()));
        int canSellSieztotal = goodsDetailAllInfo.getGoodsDetailDos().stream().mapToInt(Goods::getCanSellSize).sum();
        List<CouponTemplate> list = couponService.getDistributeTemplates(goodsCommonId,buyer);
        jsonObject.put("canSellSizeTotal", canSellSieztotal);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("goodsCommonBean", goodsDetailAllInfo.getGoodsCommon());
        jsonObject.put("couponTemplate",list);
        jsonObject.put("object", jsonObject1);
        return returnObject(jsonObject);
    }

    @RequestMapping("/app/address/add")
    public Object addAddress(@RequestParam String username,@RequestParam String address,
                             @RequestParam Integer code,@RequestParam String mobile,@RequestParam String comment,
                             @RequestParam(defaultValue = "1") Integer type,@RequestParam String tel){
        Buyer buyer = getUserByToken();
        ShippingAddress shippingAddress = new ShippingAddress();
        shippingAddress.setId(null);
        shippingAddress.setUsername(username);
        shippingAddress.setAddress(address);
        shippingAddress.setMobile(mobile);
        shippingAddress.setDetail(comment);
        shippingAddress.setType(type);
        shippingAddress.setTel(tel);
        shippingAddress.setCode(code);
        shippingAddress.setBuyerId(buyer.getId());
        if (shippingAddress.getType() == 1) {
            shippingAddressDao.updateTypeByBuyerId(0, buyer.getId());
        }
        shippingAddressDao.insert(shippingAddress);
        return returnObject(null);
    }

    @PostMapping("/app/address/del")
    public Object delAddress(@RequestParam String shippingAddressId){
        Buyer buyer = getUserByToken();
        shippingAddressDao.deleteByBuyerIdAndId(buyer.getId(),shippingAddressId);
        return returnObject(null);
    }

    @RequestMapping("/app/address/edit")
    public Object editAddress(@RequestParam Long shippingAddressId,@RequestParam String username,@RequestParam String address,
                              @RequestParam String mobile,@RequestParam String comment,
                              @RequestParam(defaultValue = "1") Integer type,@RequestParam String tel,@RequestParam Integer code){
        Buyer buyer = getUserByToken();
        ShippingAddress shippingAddress = new ShippingAddress();
        shippingAddress.setId(shippingAddressId);
        shippingAddress.setUsername(username);
        shippingAddress.setAddress(address);
        shippingAddress.setMobile(mobile);
        shippingAddress.setDetail(comment);
        shippingAddress.setType(type);
        shippingAddress.setTel(tel);
        shippingAddress.setCode(code);
        if (shippingAddress.getType() == 1) {
            shippingAddressDao.updateTypeByBuyerId(0, buyer.getId());
        }
        shippingAddressDao.updateById(shippingAddress);
        return returnObject(null);
    }

    /**
     * 获取个人收货地址
     *
     * @return
     */
    @RequestMapping("/app/address/queryV2")
    public Object queryAddress() {
        Buyer buyer = getUserByToken();
        List<ShippingAddress> list = shippingAddressDao.selectByBuyerId(buyer.getId());
        return returnList(parseAddress(list));
    }


    private JSONArray parseAddress(List<ShippingAddress> list ){
        JSONArray jsonArray = new JSONArray();
        for (ShippingAddress shippingAddress:list){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("address",shippingAddress.getAddress());
            jsonObject.put("code",shippingAddress.getCode());
            jsonObject.put("buyerId",shippingAddress.getBuyerId());
            jsonObject.put("comment",shippingAddress.getDetail()+"");
            jsonObject.put("id",shippingAddress.getId());
            jsonObject.put("mobile",shippingAddress.getMobile());
            jsonObject.put("tel",shippingAddress.getTel());
            jsonObject.put("type",shippingAddress.getType());
            jsonObject.put("username",shippingAddress.getUsername());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    /**
     * 获取自提点信息
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/api/logisticsCompany/list")
    public Object logisticList(@RequestBody JSONObject jsonObject) {
        Page page = parsePageJSON(jsonObject.getJSONObject("page"));
        JSONObject item = jsonObject.getJSONObject("item");
        Integer storeId = item.getInteger("storeId");
        Integer type = item.getInteger("type");
        List<LogisticsCompany> list = LogisticsCompanyDao.selectByStoreIdAndType(storeId, type);
        return returnList(parseLogistic(list));
    }

    private JSONArray parseLogistic(List<LogisticsCompany> list){
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String json = JSON.toJSONString(list, config);
        return JSONArray.parseArray(json);
    }

    @RequestMapping("/api/logisticsCompany")
    public Object getLogisticsCompany(@RequestBody JSONObject jsonObject) {
        Page page = parsePageJSON(jsonObject.getJSONObject("page"));
        JSONObject item = jsonObject.getJSONObject("item");
        List list = LogisticsCompanyDao.selectByStoreIdAndType(item.getInteger("storeId"), item.getInteger("type"));
        return returnList(list);
    }


    @RequestMapping("/app/order/getTransformFee")
    public Object getTransformFee(@RequestBody TransformFeeVo transformFeeVo) {
        if (transformFeeVo.getAddressId() == null) {
            return returnError("请先选择地址");
        }
        List<TransformFeeDo> list = orderService.getTransformFee(transformFeeVo);
        return returnList(list);
    }

    @RequestMapping("/app/order/confirm")
    public Object confirm(@RequestParam Long orderStoreId){
        orderService.confirm(orderStoreId);
        return returnObject(null);
    }

    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/api/shoppingCart/add")
    public Object addShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        Buyer buyer = getUserByToken();
        if (buyer != null) {
            shoppingCart.setBuyerId(buyer.getId());
            shoppingCart.setCreateTime(System.currentTimeMillis() / 1000);
            shoppingCartService.add(shoppingCart);
        }
        return returnObject(null);

    }

    /**
     * 更新购物车数量
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/api/shoppingCart/update")
    public Object updateShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        Buyer buyer = getUserByToken();
        List<ShoppingCart> list = shoppingCartMapper.selectByBuyerIdAndGoodsId(buyer.getId(), shoppingCart.getGoodsId());
        shoppingCartService.addNum(shoppingCart.getNum(), list.get(0).getId());
        return returnObject(null);
    }

    @PostMapping("/api/shoppingCart/delete")
    public Object shoppingCartDelete(@RequestParam String goodsIds){
        Buyer buyer = getUserByToken();
        shoppingCartMapper.deleteByBuyerIdAndGoodsIds(buyer.getId(),goodsIds);
        return returnObject(null);
    }


    @RequestMapping("/app/shoppingCart/createTrade")
    public Object creatTrade(@RequestBody JSONObject jsonObject) {
        Buyer buyer = getUserByToken();
        Long shippingAddressId = jsonObject.getLong("shippingAddressId");
        Long logisticsCompanyId = jsonObject.getLong("logisticsCompanyId");
        String recvName = jsonObject.getString("recvName");
        String recvMobile = jsonObject.getString("recvMobile");
        String code = jsonObject.getString("couponName");
        if (shippingAddressId==null && StringUtils.isEmpty(recvMobile)){
            return returnError("自提收货人手机号不能为空");
        }
        JSONArray orderStores = jsonObject.getJSONArray("orderTradeBeans");
        List<OrderStoreVo> orderStoreVos = new ArrayList<>();
        for (int i = 0; i <orderStores.size() ; i++) {
            JSONObject json = orderStores.getJSONObject(i);
            OrderStoreVo orderStoreVo = new OrderStoreVo();
            orderStoreVo.setComment(json.getString("comment"));
            orderStoreVo.setStoreId(json.getInteger("storeId"));
            String ids = json.getString("goodsIds");
            String[] idList = ids.split(",");
            List<OrderGoodsVo> orderGoodsVos = new ArrayList<>();
            if (Arrays.stream(idList).anyMatch(item->item.equals("21"))){
                if (StringUtils.isEmpty(code)){
                    return returnError("无效订单");
                }
                // 参加活动商品
                orderStoreVo.setCouponName(code);
                if(!activityService.checkCode(code,"14")){
                    return returnError("code已经被使用");
                }
                if(StringUtils.isEmpty(code)){
                    return returnError("特惠商品携带优惠码");
                }
                if (idList.length>1){
                    return returnError("特惠商品只能单独购买");
                }
                OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
                orderGoodsVo.setCartId(null);
                orderGoodsVo.setGoodsId(21L);
                orderGoodsVo.setNum(1);
                orderGoodsVos.add(orderGoodsVo);
            }else {
                for (String goodsId : idList) {
                    List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByBuyerIdAndGoodsId(buyer.getId(), Long.parseLong(goodsId));
                    if (shoppingCarts.size() == 0) {
                        return returnError("请勿重复提交订单");
                    }
                    for (ShoppingCart shoppingCart : shoppingCarts) {
                        OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
                        orderGoodsVo.setCartId(shoppingCart.getId());
                        orderGoodsVo.setGoodsId(shoppingCart.getGoodsId());
                        orderGoodsVo.setNum(shoppingCart.getNum());
                        orderGoodsVos.add(orderGoodsVo);
                    }
                }
            }
            orderStoreVo.setGoods(orderGoodsVos);
            orderStoreVos.add(orderStoreVo);
        }

        Trade trade = orderService.initTrade(buyer.getId());
        System.out.println(trade.toString());
        TradeVo tradeVo = new TradeVo();
        tradeVo.setLogisticsCompanyId(logisticsCompanyId);
        tradeVo.setShippingAddressId(shippingAddressId);
        tradeVo.setBuyerId(buyer.getId());
        tradeVo.setTradeId(trade.getId());
        tradeVo.setOrderStoreVos(orderStoreVos);
        tradeVo.setRecvMobile(recvMobile);
        tradeVo.setRecvName(recvName);
        trade = orderService.createTrade(tradeVo);
        return returnObject(trade);
    }

    /**
     * 获取订单信息
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/app/order/tradeStatV2")
    public JSONObject orderList(@RequestBody JSONObject jsonObject) {
        Page page = parsePageJSON(jsonObject.getJSONObject("page"));
        JSONObject item = jsonObject.getJSONObject("item");
        Integer stat = item.getInteger("stat");
        Integer type = item.getInteger("type");
        OrderStoreCondition condition = new OrderStoreCondition();
        condition.setStat(stat);
        condition.setType(type);
        Buyer buyer = getUserByToken();
        condition.setBuyerId(buyer.getId());
        IPage<OrderStoreDo> page1 = orderService.query(page, condition);
        return returnPage(page1);
    }


    @PostMapping("/app/order/detail")
    public JSONObject orderDetail(@RequestParam Long tradeId,@RequestParam Integer storeId){
        Seller seller = sellerMapper.selectOneByStoreId(storeId);
        Store store = storeMapper.selectById(storeId);
        OrderStore orderStore = orderStoreMapper.selectByStoreIdAndTradeId(storeId,tradeId);
        List<OrderGoods> list = orderGoodsMapper.selectByOrderStoreId(orderStore.getId());
        Logistics logistics = logisticsMapper.selectById(orderStore.getLogisticsId());
        JSONObject orderStoreJson = JSON.parseObject(JSON.toJSONString(orderStore));
        orderStoreJson.put("orderGoodsBeans",list);
        long payment = orderStore.getFreight()+orderStore.getPrice();
        orderStoreJson.put("payment",payment);
        orderStoreJson.put("storeName",store.getName());
        orderStoreJson.put("storePic",store.getIcon());
        orderStoreJson.put("phones",store.getPhones());
        JSONObject json = new JSONObject();
        json.put("logistics",logistics);
        json.put("orderStore",orderStoreJson);
        json.put("seller",seller);
        return returnObject(json);
    }

    /**
     * 申请退款
     *
     * @param afterSellApplyVo
     * @return
     */
    @PostMapping("/app/order/refunds")
    public Object refund(@RequestBody AfterSellApplyVo afterSellApplyVo) {
        Buyer buyer = getUserByToken();
        afterSellService.apply(afterSellApplyVo, buyer.getId());
        return returnObject(null);
    }

    @PostMapping("/app/order/dealDetail")
    public Object dealDetail(@RequestParam Long orderGoodsId){
        Buyer buyer = getUserByToken();
        List<AfterSell> list = afterSellMapper.selectByBuyerIdAndOrderGoodsId(buyer.getId(),orderGoodsId);
        if (list != null && list.size() > 0) {
            AfterSell afterSell = list.get(0);
            Store storeBean = storeMapper.selectById(afterSell.getStoreId());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("afterSell", afterSell);
            jsonObject.put("store", storeBean);
            return returnObject(jsonObject);
        }
        return returnError("无退款信息");
    }

    /**
     * 构建商品详情返回
     *
     * @param attrs
     * @return
     */
    private JSONArray attrs(List<GoodsAttrsVo> attrs) {
        if (attrs == null) return null;
        JSONArray jsonArray = new JSONArray();
        for (GoodsAttrsVo goodsAttrsVo : attrs) {
            JSONObject jsonObject = new JSONObject();
            JSONArray items = new JSONArray();
            for (int i = 0; i < goodsAttrsVo.getAttrs().size(); i++) {
                Goods2attrs goods2attrs = goodsAttrsVo.getAttrs().get(i);
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("attrId", goods2attrs.getAttrsId());
                jsonObject1.put("id", goods2attrs.getId());
                jsonObject1.put("name", goods2attrs.getName());
                jsonObject1.put("value", goods2attrs.getValue());
                jsonObject1.put("pic","");
                items.add(jsonObject1);
            }
            jsonObject.put("items", items);
            jsonObject.put("attrId", goodsAttrsVo.getAttrId());
            jsonObject.put("name", goodsAttrsVo.getName());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    /**
     * 构建商品详情返回
     *
     * @param goodsDetailDos
     * @return
     */
    private JSONArray goods(List<GoodsDetailDo> goodsDetailDos) {
        if (goodsDetailDos == null) return null;
        JSONArray jsonArray = new JSONArray();
        for (GoodsDetailDo goodsDetailDo : goodsDetailDos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("canSellSize", goodsDetailDo.getCanSellSize());
            jsonObject.put("id", goodsDetailDo.getId());
            jsonObject.put("pic","");
            jsonObject.put("price", goodsDetailDo.getPrice());
            if (goodsDetailDo.getAttr1() != null) {
                jsonObject.put("s1", Long.parseLong(goodsDetailDo.getAttr1()));
            }
            if (goodsDetailDo.getAttr2() != null) {
                jsonObject.put("s2", Long.parseLong(goodsDetailDo.getAttr2()));
            }
            if (goodsDetailDo.getAttr3() != null) {
                jsonObject.put("s3", Long.parseLong(goodsDetailDo.getAttr3()));
            }
            if (goodsDetailDo.getAttr4() != null) {
                jsonObject.put("s4", Long.parseLong(goodsDetailDo.getAttr4()));
            }
            if (goodsDetailDo.getAttr5() != null) {
                jsonObject.put("s5", Long.parseLong(goodsDetailDo.getAttr5()));
            }
            if (goodsDetailDo.getAttr6() != null) {
                jsonObject.put("s6", Long.parseLong(goodsDetailDo.getAttr6()));
            }
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }


    public JSONObject returnError(String msg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", 0);
        jsonObject.put("msg", msg);
        log.info("return error:{}",jsonObject);
        return jsonObject;
    }

    public JSONObject returnList(List list) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", 1);
        jsonObject.put("list", list);
        log.info("return list:{}",jsonObject);
        return jsonObject;
    }

    public JSONObject returnObject(Object object) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", 1);
        jsonObject.put("object", object);
        log.info("return obj:{}",jsonObject);
        return jsonObject;
    }

    public JSONObject returnPage(IPage page) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", page.getRecords());
        JSONObject pageOld = new JSONObject();
        pageOld.put("pageNo", page.getCurrent());
        pageOld.put("pageSize", page.getSize());
        pageOld.put("totalRows", page.getTotal());
        pageOld.put("totalPages",page.getPages());

        jsonObject.put("page", pageOld);
        jsonObject.put("result", 1);
        log.info("return page:{}",jsonObject);
        return jsonObject;
    }

    private Page parsePageJSON(JSONObject pageJson) {
        Page page = new Page();
        page.setPageNum(pageJson.getInteger("pageNo"));
        page.setPageSize(pageJson.getInteger("pageSize"));
        String sortOrder = pageJson.getString("sortorder");
        String sortName = pageJson.getString("sortname");
        if (!StringUtils.isEmpty(sortName)) {
            List<OrderItem> orders = new ArrayList<>();
            OrderItem orderItem = new OrderItem();
            if (StringUtils.isEmpty(sortOrder) || sortOrder.equals("desc")) {
                orderItem.setAsc(false);
            } else {
                orderItem.setAsc(true);
            }
            orderItem.setColumn(sortName);
            orders.add(orderItem);
            page.setOrders(orders);
        }
        return page;
    }
}
